#include "graphics.h"
#include "glfont.h"
#include "il.h"
#include "ilut.h"

// Begin graphics namespace
namespace graphics
{
	// Font
	GLFONT font;

	// V-Sync related declarations
	typedef void (APIENTRY *PFNWGLEXTSWAPCONTROLPROC) (int);
	typedef int (*PFNWGLEXTGETSWAPINTERVALPROC) (void);
	 
	PFNWGLEXTSWAPCONTROLPROC wglSwapIntervalEXT = NULL;
	PFNWGLEXTGETSWAPINTERVALPROC wglGetSwapIntervalEXT = NULL;

	// Initialize all APIs, resources, etc.
	void initialize()
	{
		glewInit();

		ilInit();
		ilutInit();
	}

	// Handle window resizing
	void handle_resize(int w, int h)
	{
		width = w;
		height = h;

		if (height == 0)										// Prevent A Divide By Zero By
		{
			height = 1;										// Making Height Equal One
		}

		glViewport(0, 0, w, h);

		glMatrixMode(GL_PROJECTION);

		glLoadIdentity();
		gluPerspective(45.0,
						(double)w / (double)h,
						0.01,
						10000000.0);
		glMatrixMode(GL_MODELVIEW);

		init_vsync();
		set_vsync_state(false);
	}

	// Initialize OpenGL stuff
	int init_gl()	
	{
		//glFontCreate(&font, "font.glf", 0);
		
		glShadeModel(GL_SMOOTH);							// Enable Smooth Shading (fixed function)
		glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
		glEnable(GL_BLEND);
		glEnable(GL_ALPHA);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations

		return TRUE;										// Initialization Went OK
	}

	//init VSync func
	void init_vsync()
	{
	   //get extensions of graphics card
	   char* extensions = (char*)glGetString(GL_EXTENSIONS);
	  
	   //is WGL_EXT_swap_control in the string? VSync switch possible?
	   if (strstr(extensions,"WGL_EXT_swap_control"))
	   {
		  //get address's of both functions and save them
		  wglSwapIntervalEXT = (PFNWGLEXTSWAPCONTROLPROC)
			  wglGetProcAddress("wglSwapIntervalEXT");
		  wglGetSwapIntervalEXT = (PFNWGLEXTGETSWAPINTERVALPROC)
			  wglGetProcAddress("wglGetSwapIntervalEXT");
	  }
	}

	bool vsync_enabled()
	{
	   //if interval is positif, it is not 0 so enabled ;)
	   return (wglGetSwapIntervalEXT() > 0);
	}
	 
	void set_vsync_state(bool enable)
	{
		if (enable)
		   wglSwapIntervalEXT(1); // set interval to 1 to enable
		else
		   wglSwapIntervalEXT(0); // disable
	}

}
// End graphics namespace